package me.gacl.demo;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

import me.gacl.utils.ResultSetHandler;


/**
* @ClassName: BeanListHandler
* @Description: 将结果集转换成bean对象的list集合的处理器
* @author: 孤傲苍狼
* @date: 2014-10-5 下午12:00:06
*
*/ 
public class BeanListHandler implements ResultSetHandler {

	private Class<?> clazz;
	public BeanListHandler(Class<?> clazz) {
		// TODO Auto-generated constructor stub
		this.clazz = clazz;
	}
	
	@Override
	public Object handler(ResultSet rs) {
		// TODO Auto-generated method stub
		try {
			List<Object> list = new ArrayList<Object>();
			while(rs.next()) {
				Object bean = clazz.newInstance();
				
				ResultSetMetaData metadata = rs.getMetaData();
				int count = metadata.getColumnCount();
				for(int i = 0; i < count; i++) {
					String name = metadata.getColumnName(i+1);
					Object value = rs.getObject(name);
					Field f = bean.getClass().getDeclaredField(name);
					f.setAccessible(true);
					f.set(bean, value);
				}
				list.add(bean);
			}
			return list.size() > 0 ? list : null;
			
		} catch (Exception e) {
			// TODO: handle exception
			throw new RuntimeException(e);
		}
	}

}
